/*
 * @Description  : 侧边栏组件
 * @Author       : Keyman
 * @Date         : 2025-11-11 22:26:05
 * @LastEditors  : Keyman
 * @LastEditTime : 2025-11-20 18:59:58
 */

import { Menu } from "antd";
import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { icons } from "./iconList";
import logo from "../../assets/logo.png";
import "./index.scss";
import { useLocation, useNavigate } from "react-router-dom";

type MenuItem = {
  key: string;
  label: string;
  children?: MenuItem[];
  icon: string;
};

function Sidebar() {
  const { menuList } = useSelector((state: any) => state.authSlice);
  const [menuData, setMenuData] = useState<MenuItem[]>([]);
  const navigate = useNavigate();
  const location = useLocation();
  useEffect(() => {
    getItem();
  }, [menuList]);

  async function getItem() {
    setMenuData(
      menuList.map((items: MenuItem) => {
        // 处理后台返回数据
        if (!items) return null;
        return {
          key: items.key,
          label: items.label,
          icon: icons[items.icon],
          children: items.children?.map((children) => {
            return {
              key: children.key || null,
              label: children.label || null,
            };
          }),
        };
      })
    );
  }

  function handleClick({ key }: { key: string }) {
    navigate(key);
  }

  return (
    <div className="sidebar">
      <div className="logo">
        <img src={logo} alt="logo" width={18} />
        <h1>鹏远智慧园区</h1>
      </div>
      <Menu
        defaultSelectedKeys={["/dashboard"]}
        mode="inline"
        theme="dark"
        items={menuData}
        onClick={handleClick}
        selectedKeys={[location.pathname]}
      />
    </div>
  );
}

export default Sidebar;
